<template>
  <div class="vue-box">
    <div class="c-panel">
      <el-row>
        <!--模糊查询-->
        <el-form :inline="true" size="small">
              <el-form-item label="部门名称：">
                <el-input type="text" size="small" v-model="query.orgName" placeholder="模糊查询"></el-input>
              </el-form-item>
              <el-form-item label="部门状态：">
                <el-select size="small" v-model="query.status" placeholder="请选择" clearable>
                  <el-option label="启用" value="1"></el-option>
                  <el-option label="停用" value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button style="min-width: 0px;" type="primary" icon="el-icon-search" @click="screen()">查询</el-button>
              </el-form-item>
        </el-form>
        <!--全局功能按钮-->
        <el-row>
            <el-col :span="1.5" class="firstBtn">
              <el-button size="small" type="success" icon="el-icon-plus" plain @click="add('')">新增</el-button>
            </el-col>
            <el-col :span="1.5" class="btn">
              <el-button size="small" type="info" icon="el-icon-refresh" plain @click="query.orgName='',query.status='',load()">重置</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button size="small" type="primary" icon="el-icon-cloudy" plain @click="openWarning('还在构思中哦0.0')">占坑</el-button>
            </el-col>
        </el-row>
        <!--组织列表-->
        <el-table
          :data="tableData" style="width: 100%" row-key="orgid" ref="table" v-loading="state.loading" element-loading-text="拼命加载中"
          @expand-change="goLoad"
          lazy :load="load" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column prop="orgName" label="部门名称" width="140">
          </el-table-column>
          <el-table-column prop="orderNum" label="显示顺序" width="100">
          </el-table-column>
          <el-table-column prop="leaderName" label="负责人" width="140">
          </el-table-column>
          <!--<el-table-column prop="leaderEmail" label="负责人邮箱" width="200">
          </el-table-column>-->
          <el-table-column label="状态" prop="tag" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status === '启用' ? 'primary' : 'info'"
                disable-transitions>{{scope.row.status}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" label="部门创建人" width="140">
          </el-table-column>
          <el-table-column prop="createTime" label="部门创建时间" width="200">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <!--是否是三级部门或编外部门（是则禁止进行新增操作-->
              <el-button :disabled="!idList.includes(scope.row.orgid) || scope.row.orgid=='1571514747092729857'"
                size="mini" type="success"
                @click="add(scope.row,'rowadd')"><i class="el-icon-plus el-icon--left"></i>新增</el-button>
              <el-button size="mini" type="primary"
                @click="edit(scope.row)"><i class="el-icon-edit el-icon--left"></i>修改</el-button>
              <!--是否是一级部门或编外部门（是则禁止进行删除操作-->
              <el-button
                size="mini" type="danger" :disabled="rootId==scope.row.orgid || scope.row.orgid=='1571514747092729857'"
                @click="state.delDialogVisible=true,info=scope.row,openWarning('此操作会导致该部门的下级部门也会被删除!')"><i class="el-icon-delete el-icon--left"></i>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--对话框相关-->
        <el-dialog title="部门信息 " v-if="state.dialogVisible" :visible.sync="state.dialogVisible" :modal-append-to-body='false'
        top='5vh'>
            <org-info :idList="idList" :nameList="nameList" :org="JSON.stringify(info)" :displayType="state.displayType" :addType="state.addType"></org-info>
        </el-dialog>
        <el-dialog title="删除提示" :visible.sync="state.delDialogVisible" :modal-append-to-body='false'
        width="30%" :before-close="handleClose">
              <span >确定删除该部门？</span>
              <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="del()">确 定</el-button>
                <el-button @click="state.delDialogVisible=false">取 消</el-button>
              </span>
        </el-dialog>
      </el-row>
    </div>
  </div>
    
</template>
<script>
import orgInfo from './org-info.vue';
  export default {
  components: { orgInfo },
    data() {
        return {
          /* 数据相关 */
          //组织数据
          tableData:[],
          rootId:'',
          //一二级组织id和name，供修改/添加上级组织
          idList:[],
          nameList:[],
          //节点对应的树对象
          map:new Map(),
          //查询参数
          query:{
            orgName:'',
            status:''
          },
          //当前操作组织数据
          info:{},
          /* 各种状态 */
          state:{
            loading:true,
            displayType:'edit',
            addType:'',
            delDialogVisible:false,
            dialogVisible:false,
            
          }
        }
    },
    methods: {
        //组织树初始化及树形节点的懒加载
        load(tree, treeNode, resolve) {
          this.state.loading=true;
          //console.log("load");
          //当前节点数据
          //console.log(tree);
          //当前节点的层级信息
          //console.log(treeNode);
          //console.log(resolve);
          //tree为空则是初始化，不为空则是展开某一节点
          if(tree !== undefined){
            let params=tree.id;
            this.request('/api/org/getSeniorOrg?id='+params).then(res=>{
              if(!res){return}
              //此处是为了给树结构一个唯一索引，对应标签属性，用id会报错。。
              res.data.forEach(element => {
                element.orgid=element.id
                element=this.sa.displaceStrStatus(element)
              });
              //console.log(res.data);
              let status=true
              resolve(//这玩意里面就是子结构的对象，赋值就完事了
                  res.data
              )
              //存放当前节点的树结构数据
              this.map.set(tree.id, { tree, treeNode, resolve ,status});
            })
          }else{//初始化(打开页面时，不是展开一级节点
            this.request('/api/org/getSeniorOrg?id=').then(res=>{
              if(!res){return}
              if(res.data!=null&&res.data!=undefined){
                if(res.data.flag===true){
                  res.data.retData.hasChildren=true;
                  res.data.retData.orgid=res.data.retData.id
                  this.rootId=res.data.retData.id
                }
                res.data.retData=this.sa.displaceStrStatus(res.data.retData)
                this.tableData=[res.data.retData]
              }else{
                this.tableData=[]
              }
            })
          }
          this.state.loading=false;
        },
        //手动加载
        goLoad(row,openStatus){
            this.state.loading=true;
            //console.log(this.map.get(1));//get不出来，这个方法和lazyLoad是并行，map还没值的，但是log出来是map有值，感觉log应该是等所有程序走完再走
            //console.log(row);//当前点击行
            //console.log(params);//点击后，行的展开状态，布尔值
            //这个触发条件是点击行后的状态为展开，该行在map中已有值（非初始化），且当前行上一次的状态为折叠（这个参数尤为重要
            if(openStatus&&this.map.get(row.id)!==undefined&&!this.map.get(row.id).status){
              //展开
              //console.log("goLoad");
              this.request('/api/org/getSeniorOrg?id='+row.id).then(res=>{
                if(!res){return}
                res.data.forEach(element => {
                  element.orgid=element.id
                  element=this.sa.displaceStrStatus(element)
                });
                let org=this.map.get(row.id)
                org.status=openStatus;
                org.resolve(res.data)
                //更新map中数据
                this.map.set(row.id, org);
              })
            }
            //如果当前点击行的状态为收起，更新map中的该行当前状态
            if(openStatus===false&&this.map.get(row.id)!==undefined){
              //console.log("updateOpen");
              let org=this.map.get(row.id)
              org.status=openStatus;
              this.map.set(row.id, org);
            }
            this.state.loading=false;
        },
        //修改
        edit(data){
          if(this.zm.checkAuth('org:update')){
            this.info=data;
            this.state.displayType="edit";
            //console.log(this.info);
            this.state.dialogVisible=true;
          }else{
            this.$message.error("您暂无<修改部门>权限！")
          }
          
        },
        //修改的回调
        updateCallback(originId,newPid){
          this.$message.success("修改成功")
          this.state.loading=true;
          this.state.dialogVisible=false
          //console.log(newPid);
          //页面的数据
          //console.log(this.$refs.table.store.states.lazyTreeNodeMap);
          //如果修改的是根组织，直接重新进行初始化操作
          if(originId=='0'){
            this.load()
          }else{//如果修改的是子组织
            //刷新原上级节点
            this.refreshLoadTree(originId);
            let data=this.map.get(newPid)
            //此时代表新上级组织原本无下级组织或，有下级组织但未展开
            if(data===undefined){
                let params=newPid;
                this.request('',params).then(res=>{
                  if(!res){return}
                  let pid=res.data.parentId;
                  //获取新上级组织的上级组织，将新上级组织的是否包含子级状态修改并重新赋值
                  let treeArr=this.$refs.table.store.states.lazyTreeNodeMap[pid];
                  //console.log(treeArr);
                  for (let index = 0; index < treeArr.length; index++) {
                    const element = treeArr[index];
                    if(element.orgid==newPid){
                      treeArr[index].hasChildren=true;
                    }
                  }
                  this.$refs.table.store.states.lazyTreeNodeMap[pid]=treeArr;
                })
            }else{
              //如果新上级组织的当前状态为展开时,刷新
                if(data.status){
                  this.refreshLoadTree(newPid);
                }
            }
          }
          //console.log(this.$refs.table.store.states.lazyTreeNodeMap);
          this.state.loading=false;
        },
        //新增
        add(data,type){
          //console.log(data);
          if(this.zm.checkAuth('org:add')){
            this.info=data;
            this.state.displayType="add";
            //如果是组织行新增，则父级组织固定
            if(type==="rowadd"){
              this.state.addType="rowadd"
            }else{
              this.state.addType=""
            }
            this.state.dialogVisible=true;
          }else{
            this.$message.error("您暂无<新增部门>权限！")
          }
          
        },
        //新增的回调
        addCallback(newPid){
          let data=this.map.get(newPid)
          //此时代表新上级组织原本无下级组织或，有下级组织但未展开
          if(data===undefined){
              let params=newPid;
              this.request('/api/org/getPid?id='+params,params).then(res=>{
                if(!res){return}
                let pid=response.data.data.parentId;
                //获取新上级组织的上级组织，将新上级组织的是否包含子级状态修改并重新赋值
                let treeArr=this.$refs.table.store.states.lazyTreeNodeMap[pid];
                //console.log(treeArr);
                for (let index = 0; index < treeArr.length; index++) {
                  const element = treeArr[index];
                  if(element.orgid==newPid){
                    treeArr[index].hasChildren=true;
                  }
                }
                this.$refs.table.store.states.lazyTreeNodeMap[pid]=treeArr;
              })
          }else{
            //如果新上级组织的当前状态为展开时刷新
              if(data.status){
                this.refreshLoadTree(newPid);
              }
          }
          this.$message.success("新增成功")
          this.state.dialogVisible=false;
        },
        //删除
        del(){
          this.sa.loading("删除中...");
          //console.log(this.info);
          //this.info.status='-1';
          let params=this.info;
          params.status="-1"
          //console.log(params);
          this.request('/api/org/del',params).then(res=>{
            if(!res){return}
            this.state.delDialogVisible=false;
            let flag=this.sa.if403(res)
            if(params.parentId!="0"){
              this.refreshLoadTree(params.parentId)
            }
            this.$message.success("删除成功")
          })
          this.sa.hideloading();
        },
        //模糊查询
        screen(){
          let params=this.query;        
          if(params.status===''&&params.orgName===''){
            return;
          }
          console.log(params)
          //console.log(params);
          this.request('/api/org/screen',params).then(res=>{
            if(!res){return}
            res.data.forEach(element => {
              element.orgid=element.id
              element=this.sa.displaceStrStatus(element)
            });
            //console.log(res);
            this.tableData=res.data
          })
        },
        //节点局部刷新（刷新当前操作节点的父节点
        refreshLoadTree(pid) {
          console.log("refresh");
          //console.log(this.map);
          //console.log(pid);
          // 根据更改节点的父ID取出相应数据,这里id要转int（key的类型
          
          const treeMap = this.map.get(pid);
          console.log(treeMap);//修改一级组织这里为空
          const tree=treeMap.tree;
          const treeNode=treeMap.treeNode;
          const resolve=treeMap.resolve;
          //console.log(this);
          this.$set(
            // 不要忘记在你的table上写ref
            this.$refs.table.store.states.lazyTreeNodeMap, 
            pid,
            []
          );
          //console.log(tree);
          //console.log(this.$refs.table.store.states.lazyTreeNodeMap);
          if (tree) {
            // 将取出对应数据再传给load方法（重新加载当前操作节点的父节点
            this.load(tree, treeNode, resolve); 
          }
        },
        //弹出警告提示框，参数为警告信息
        openWarning(msg) {
          this.$notify({
            title: '警告',
            message: msg,
            type: 'warning'
          });
        },
        //对话框取消
        handleClose(done) {
          this.$confirm('确认关闭？')
            .then(_ => {
            done();
            })
            .catch(_ => {});
        }
    },
    mounted(){
        this.load()
        //获取一二级组织id和name数组，别问为啥不传对象数组，点一次就得遍历一次，麻，这就直接includes
        this.request('/api/org/getOneAndTwoLevelOrg').then(res=>{
          if(!res){return}
          this.idList=res.data.idList
          this.nameList=res.data.nameList
        })
        this.$bus.$on("updateOrgCallback",this.updateCallback)
        this.$bus.$on("addOrgCallback",this.addCallback)
        this.$bus.$on("noUpdate",()=>{
          this.state.dialogVisible=false;
        })
        this.state.loading=false;
    },
    beforeDestroy(){
      //组件销毁时解绑全局事件，否则再次初始化组件会重复挂载，多次触发本该触发一次的方法（如修改回调
      //console.log("go?");
      this.$bus.$off(['updateOrgCallback','addOrgCallback','noUpdate'])
    }
  }
</script>
<style scoped>
/**模糊查询样式*/
.el-form-item--small /deep/ .el-form-item__content, /deep/ .el-form-item--small .el-form-item__label  {
	font-size:14px;
	font-weight:900;
}
/*表格样式 */
/deep/ .el-table {
  margin-left:10px;
}
/deep/ .el-table th.el-table__cell {
  background-color: aliceblue;
}
/*模糊搜索表单右移5px，对齐全局按钮和数据table*/
/deep/.c-panel .el-form{
	margin-left:-5px
}
/*按钮与表格的对齐间距等等 */
.firstBtn{
  padding-left:10px;
  padding-right:5px;
  margin-bottom: 5px;
}
.btn{
  padding-right:5px;
  margin-bottom: 5px;
}
</style>